package model

import (
	"common/globals"
	"gorm.io/gorm"
)

type UserCoupon struct {
	gorm.Model
	UserId            int     `gorm:"column:user_id;type:int(11);not null" json:"user_id"`
	CouponId          int     `gorm:"column:coupon_id;type:int(11);not null" json:"coupon_id"`
	CouponPrice       float64 `gorm:"column:coupon_price;type:decimal(10,2);not null" json:"coupon_price"`
	HowMoneyAvailable float64 `gorm:"column:how_money_available;type:decimal(10,2);not null" json:"how_money_available"`
	Status            string  `gorm:"column:status;type:enum('已过期','未过期','已使用');not null;default:'未过期'" json:"status"`
}

func (u *UserCoupon) TableName() string {
	return "user_coupon"
}
func (u *UserCoupon) Create() error {
	return globals.Db.Create(&u).Error
}
func (u *UserCoupon) GetCouponByUserIdAndStatus(userId int, status string) ([]UserCoupon, error) {
	var userCoupons []UserCoupon
	if status == "" {
		err := globals.Db.Where("user_id = ?", userId).Find(&userCoupons).Error
		return userCoupons, err
	} else {
		err := globals.Db.Where("user_id = ? and status = ?", userId, status).Find(&userCoupons).Error
		return userCoupons, err
	}
}
func (u *UserCoupon) GetCouponById(Id int) error {
	return globals.Db.Where("id = ?", Id).Limit(1).Find(&u).Error
}
func (u *UserCoupon) GetCouponByCouponIdAndUserId(couponId, userid int) error {
	return globals.Db.Where("coupon_id = ? and user_id = ?", couponId, userid).Limit(1).Find(&u).Error
}
func (u *UserCoupon) UpdateStatusById(id int, status string) error {
	return globals.Db.Model(&UserCoupon{}).Where("id = ?", id).Update("status", status).Error
}
